// components/chat/chat.js
import imClient from '../../utils/im-client'
let that = null
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    show: { // 属性名
      type: Boolean,
      value: false
    },
  },

  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
      that = this
      imClient.$on('TEXT_MESSAGE_GROUP',this.messageEvent)
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
      imClient.$off('TEXT_MESSAGE_GROUP',this.messageEvent)
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    chatBottom: 0,
    messageList: [],
    message: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    async sendMsg (event) {
      const { value } = event.detail
      this.setData({
        message:value
      })
      if (this.data.message) {
        const res = await imClient.sendDefaultMessage({ text: this.data.message })
        const msgList = this.data.messageList
        msgList.push({
          userType: '0',
          text: res.data.message.payload.text,
          nickname: res.data.message.nick || '我'
        })
        this.setData({
          messageList: msgList,
          message: ''
        })
      }
    },
    messageEvent (res) {
      if (res.length > 0) {
        const msgList = that.data.messageList
        res.forEach(item => {
          msgList.push({
            userType: '1',
            text: item.payload.text,
            nickname: item.nick || '客户'
          })
        })
        that.setData({
          messageList:msgList
        })
      }
    },
    closeHandle(){
      this.triggerEvent('updateData', {msgWindow:false})
    }
  }
})
